package com.webxiaohua.algorithm.sort;

import java.util.Random;

/**
 * @author shenxinhua
 * @date 2019-06-22 17:32
 * @desc 冒泡排序算法
 */
public class MaopaoSort {

    public static int[] generateArray(int length){
        int[] array = new int[length];
        Random random = new Random();
        for(int i=0;i<array.length;i++){
            array[i] = random.nextInt(100000);
        }
        return array;
    }

    public static void main(String... args){
        int[] array = generateArray(100);
        // 记录循环次数
        int counts = 0;
        long start = System.currentTimeMillis();
        // 外层循环控制轮数
        for(int i=0;i < array.length-1;i++){
            // 内层循环控制每一轮比较次数
            for(int j=0;j < array.length-1-i;j++){
                counts++;
                if(array[j] > array[j+1]){
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j + 1] = tmp;
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("共排序："+counts+"次,耗时："+(end - start)+"毫秒");
        for (int i: array) {
            System.out.println(i);
        }
    }
}
